//#include "StdAfx.h"
#include "BasicMemoryAlloc.h"

namespace utility
{

	BasicBlockMemory::BasicBlockMemory(int block_num, int block_size )
	{
		m_block_num  = block_num;
		m_block_size = block_size;
		m_pInitBuf  = new char[m_block_num*m_block_size];
		assert( m_pInitBuf != NULL );
		m_pMemAllocFlag = new PMemAllocFlag[m_block_num];
		for( int i = 0; i < m_block_num; i++ )
		{
			m_pMemAllocFlag[i] = new SMemAllocFlag;
			char * p = m_pInitBuf + i*m_block_size;
			m_pMemAllocFlag[i]->init( p, m_block_size );
		}
	}
	BasicBlockMemory::~BasicBlockMemory(void)
	{
		for( int i = 0; i < m_block_num; i++ )
		{
			delete m_pMemAllocFlag[i];
		}
		delete []m_pMemAllocFlag;

		if( m_pInitBuf != NULL )
			delete []m_pInitBuf;
	}
	void * BasicBlockMemory::Alloc( int size )
	{
		if( size > m_block_size )
			return NULL;

		void * p = NULL;
		m_optex.Enter();
		for( int i = 0; i < m_block_num; i++ )
		{
			if( !m_pMemAllocFlag[i]->m_flag )
			{
				p = m_pMemAllocFlag[i]->alloc();
				break;
			}
		}
		m_optex.Leave();

		if( p == NULL )
			p = new char[size];
		return p;
	}
	void BasicBlockMemory::Free( void * p )
	{
		bool bFree = false;
		m_optex.Enter();
		for( int i = 0; i < m_block_num; i++ )
		{
			if( m_pMemAllocFlag[i]->m_p == p )
			{
				m_pMemAllocFlag[i]->free();
				bFree = true;
				break;
			}
		}
		m_optex.Leave();
		if( !bFree )
			delete [](char*)p;
	}


}
